import React, { Component } from "react";
import { StyleSheet, View, Text, TouchableOpacity, Button } from "react-native";
import { connect, Provider } from "react-redux";
import { plus, minus } from "./redux/action";
import { getStore } from "./redux/configStore";

let store = getStore();

const styles = StyleSheet.create({
  button: {
    width: 100,
    // height: 30,
    padding: 10,
    backgroundColor: "lightgray",
    alignItems: "center",
    justifyContent: "center",
    margin: 3
  }
});

export default class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      maximumTimes: 100,
      currentTimes: 0
    };
  }

  componentDidMount = () => {
    this.start();
  };

  start = () => {
    const { currentTimes, maximumTimes } = this.state;
    setTimeout(() => {
      this.setState({ currentTimes: currentTimes + 1 });
      this.plusOne();
      if (currentTimes < maximumTimes) {
        this.start();
      }
    }, 1000);
  };

  plusOne = () => {
    console.log('plus one');
    store.dispatch(plus(1));
  };

  render() {
    const { counter, increment, decrement } = this.props;

    return (
      <Provider store={store} ref={this.provider}>
        <View
          style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
        >
          <ReduxCounterItem />
          <ReduxCounterItem />
          <ReduxCounterItem />
        </View>
      </Provider>
    );
  }
}

class CounterItem extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  plus = () => {
    // this.setState({ counter: this.state.counter + 1 });
    this.props.dispatch(plus(1));
  };

  minus = () => {
    this.props.dispatch(minus(1));
  };

  render() {
    return (
      <View style={{ flexDirection: "row", alignItems: "center" }}>
        <Text>计数器：</Text>
        <Text>{this.props.calculator.c}</Text>
        <Button
          onPress={() => {
            this.plus();
          }}
          title={"点我增加"}
          style={{}}
        />
        <Button
          onPress={() => {
            this.minus();
          }}
          title={"点我减少"}
          style={{}}
        />
      </View>
    );
  }
}

// store = {
//   calculator: {c: 12},
//   navi: {id: name},
//   ...
// }

// state map to prop
const mapStateToProps = state => {
  return {
    // state.xxx 必须和reducer同名
    calculator: state.calculator
  };
};

const ReduxCounterItem = connect(mapStateToProps)(CounterItem);
